<template>
    <!-- 顶部菜单 -->
    <!-- <div class="top-menus" v-if="topMenus.length">
        <template v-for="item in topMenus" :key="item.code">
            <div
                v-if="!item.isHide"
                class="item"
                :style="{ backgroundImage: `url(${img3})` }"
                :class="{ active: currentMenuInfo.top === item.code }"
                @click="onClickTopMenu(item)"
            >
                <span class="text"> {{ item.name }}</span>
            </div>
        </template>
    </div> -->
    <!-- 底部-更多菜单 -->
    <el-collapse-transition>
        <div
            v-if="isShowMore"
            class="bottom-menus-more-pop"
            :style="{ backgroundImage: `url(${img1})` }"
        >
            <div
                v-for="item in bottomPopMenus"
                :key="item.code"
                class="item"
                :class="{ active: currentMenuInfo.bottom === item.code }"
                @click="onClickBottomMenu(item)"
            >
                <span class="text"> {{ item.name }}</span>
            </div>
        </div>
    </el-collapse-transition>
    <!-- 底部菜单 -->
    <div class="bottom-menus">
        <div
            v-for="item in bottomShowMenus"
            :key="item.code"
            class="item"
            :class="{ active: currentMenuInfo.bottom === item.code }"
            @click="onClickBottomMenu(item)"
            :style="{
                marginLeft:
                    bottomShowMenus.length > 7
                        ? '20px'
                        : bottomShowMenus.length > 2
                          ? bottomShowMenus.length > 6
                              ? '50px'
                              : '100px'
                          : '180px',
            }"
        >
            {{ item.name }}
        </div>
    </div>
</template>

<script setup lang="ts">
import config from '@/config'
import { getPublicImageAssetsFile } from '@/utils/tools'
import dayjs from 'dayjs'
import { getToken } from '@/utils/tools'

// 路由
const router = useRouter()
const route = useRoute()

// 图片
// const img1 = getPublicImageAssetsFile('bottom-menus-pop-bg.png')
const img1 = getPublicImageAssetsFile('bottom-menus-pop-bg1.png')
const img2 = getPublicImageAssetsFile('menu-item-bg.png')
const img3 = getPublicImageAssetsFile('top-menu-item-bg.png')

/**
 * 菜单定义
 * 存在 isOutlink = true 均是跳转到外部的链接
 * 存在subs的菜单，是通过微前端接入的子菜单
 */
const transformSystemMenus = () => {
    if (window.systemMenusList) {
        const worker = (list: any[]): any[] => {
            return list.map((item: any) => {
                const isOutlink = Boolean(item.url && item.url.includes('OUT_LINK'))
                let url = item.url.replace('OUT_LINK=', '').trim()
                // 淳安秀水卫视特殊处理
                if (item.key === 'xiushuiGuardian') {
                    // url = `${url}?jump=true&timeStamp=${dayjs().valueOf()}&accountId=77831857`
                    url = `${url}?timeStamp=${dayjs().valueOf()}&accountId=77831857`
                } else if (item.key === 'videoCenter') {
                    // 视频中心
                    url = `${url}?token=${getToken()}`
                } else if (['water', 'gas', 'noise'].includes(item.key)) {
                    url = `${url}?isSubScene=true`
                } else {
                    url = url.indexOf('token') > -1 ? url : `${url}?token=${getToken()}`
                }
                return {
                    name: item.label,
                    code: item.code,
                    parentCode: item.parentId,
                    url,
                    isOutlink: item.subs && item.subs.length ? false : isOutlink,
                    subs: item.subs && item.subs.length ? worker(item.subs) : [],
                    hidden: item.hidden,
                }
            })
        }
        return worker(window.systemMenusList)
    }
    return []
}

const allMenus = shallowRef(transformSystemMenus())

const allMenusByPanel: any = shallowRef([])

// 路径映射编码
const pathMappingCode: any = {}
const worker = (list: any[]) => {
    list.forEach(item => {
        if (item.parentCode && item.code && item.url) {
            pathMappingCode[item.url] = {
                code: item.code,
                parentCode: item.parentCode,
            }
        }
        if (item.subs) {
            worker(item.subs)
        }
    })
}
worker(allMenus.value)

const menusObj: any = {
    'stzwPowerfulScreen::global': ['空气', '秀水', '生态', '督察', '服务'],
    'stzwPowerfulScreen::gas': [
        '空气',
        '噪声',
        '环境监测',
        '遥感监测',
        '飞航监测',
        '高空瞭望',
        '移动监测',
        '扬尘在线',
        '乡镇网格化',
        '活性炭监管',
        '车检服务',
        '重大保障',
    ],
    'stzwPowerfulScreen::water': [
        '秀水',
        '淳安秀水卫士',
        '环境监测',
        '遥感监测',
        '飞航监测',
        '高空瞭望',
        '重大保障',
    ],
    'stzwPowerfulScreen::earthNew': ['净土', '遥感监测', '飞航监测', '地下水平台', '环检码'],
    'stzwPowerfulScreen::slag': ['无废', '危废智治', '环检码'],
    'stzwPowerfulScreen::radiation': ['辐射', '环检码'],
    'stzwPowerfulScreen::superintend': ['督察', '执法', '应急', '车检服务', '办案助手'],
    'stzwPowerfulScreen::law': ['执法', '应急', '车检服务', '办案助手'],
    'stzwPowerfulScreen::monitor': [
        '环境监测',
        '遥感监测',
        '飞航监测',
        '高空瞭望',
        '移动监测',
        '物联感知',
        '扬尘在线',
        '乡镇网格化',
        '地下水平台',
        '环检码',
        '车检服务',
        '空气',
        '秀水',
        '噪声',
        '净土',
    ],
    'stzwPowerfulScreen::beautifulHz': ['生态', '遥感监测'],
    'stzwPowerfulScreen::envSerivice': ['智管服', '准入', '绿色产业', '环评助手', '环检码'],
    'stzwPowerfulScreen::carbon': ['双碳'],
    'stzwPowerfulScreen::greenDevelopment': [
        '智管服',
        '准入',
        '环检码',
        '绿色产业',
        '环评助手',
        '双碳',
    ],
    'stzwPowerfulScreen::ecologicalBrain': ['数小助', '绩小助', '视频中心'],
}

let subPopName: any = ''

// 监听点击的面板
const watchNameChange = (newValue?: any) => {
    // let menus = []
    // if(newValue) {
    //     const key = newValue
    //     key ? menus = menusObj[key] : ''
    // } else {
    //     menus = menusObj['stzwPowerfulScreen::global']
    // }

    // allMenusByPanel.value = allMenus.value.filter((item: any) => menus.includes(item.name))
    // if(menus.length > allMenusByPanel.value.length) {
    //     // 暂时没有配置的菜单（先写死，之后走bsp统一）
    //     const names = allMenusByPanel.value.map((v: any) => v.name)
    //     const filterMenus = menus.filter((v: any) => !names.includes(v))
    //     filterMenus.forEach((item: any, index: any) => {
    //         allMenusByPanel.value.push({
    //             name: item,
    //             code: `codecode${index}`
    //         })
    //     })

    // }

    // 走接口 bsp
    const subs =
        allMenus.value.find((item: any) => item.code === (newValue || 'stzwPowerfulScreen::global'))
            ?.subs || []
    // 过滤掉隐藏的菜单
    allMenusByPanel.value = subs.filter((item: any) => !item.hidden)
}

// 是否展示更多弹窗
const isShowMore = ref(false)

onMounted(() => {
    // 基座应用中监听 storage 事件
    window.addEventListener('storage', (event: any) => {
        if (event.key === 'subapp-store') {
            isShowMore.value = false
            subPopName = event.newValue
            watchNameChange(subPopName)
        }
    })
    // 首次进入，选中对应菜单
    const codeInfo = pathMappingCode[route.path]
    if (codeInfo) {
        currentMenuInfo.bottom = codeInfo.parentCode
        currentMenuInfo.top = codeInfo.code
    }
})

watch(
    subPopName,
    () => {
        isShowMore.value = false
        watchNameChange(subPopName)
    },
    {
        immediate: true,
    },
)
// 当前选择的菜单数据
const currentMenuInfo = reactive({
    bottom: '',
    top: '',
})

// 底部更多菜单
const bottomPopMenus = computed(() => {
    if (!subPopName) {
        // // 目前都写死假的。来不及配菜单
        // const strNames = allMenusByPanel.value.map((v: any) => v.name)
        // const falseData: any = ['噪声', '净土', '无废', '辐射', '双碳', '督察', '执法', '应急', '准入', '重大保障', '环检码', '车检服务', '绿色产业', '环评助手', '办案助手',  '环境监测', '遥感监测', '飞航监测', '高空瞭望', '移动监测', '物联感知', '扬尘在线', '乡镇网格化', '活性炭监管', '地下水平台', '淳安秀水卫士', '危废智治', '数小助', '绩小助', '视频中心']; // 假数据
        // //   const filterMenus = allMenus.value.filter((item: any) => !strNames.includes(item.name))
        // const filterMenus = allMenus.value.filter((item: any) => !strNames.includes(item.name))
        // const filterUrl = filterMenus.filter((v: any) => v.url)
        // const names = filterUrl.map((v: any) => v.name)
        // falseData.forEach((item: any, index: any) => {
        //     if(!names.includes(item)) {
        //         filterUrl.push({
        //             name: item,
        //             code: `codecodecode${index}`
        //         })
        //     }
        // })

        // 走bsp接口
        return allMenusByPanel.value.slice(5)
    } else {
        return allMenusByPanel.value.slice(5)
    }
})

// 底部显示的菜单
const bottomShowMenus = computed(() => {
    // 全局  或者 点击面板
    return !subPopName
        ? [
              ...allMenusByPanel.value.slice(0, 5),
              {
                  name: '更多',
                  code: 'more-menu',
              },
          ]
        : allMenusByPanel.value.length > 5
          ? [
                ...allMenusByPanel.value.slice(0, 5),
                {
                    name: '更多',
                    code: 'more-menu',
                },
            ]
          : allMenusByPanel.value
})

// 顶部按钮
const topMenus = computed(() => {
    const findObj = allMenus.value.find(c => c.code === currentMenuInfo.bottom)
    if (findObj && findObj.subs && findObj.subs.length) {
        return findObj.subs
    }
    return []
})

// 点击底部菜单
const onClickBottomMenu = (info: any) => {
    if (info.code === 'more-menu') {
        isShowMore.value = !isShowMore.value
    } else if (info.isOutlink) {
        const path =
            info.url.includes('http') || info.url.includes('https')
                ? info.url
                : `${config.outLinkDefaultRootPath}${info.url}`
        console.log('pathpath', path)
        window.open(path, '_blank')
        isShowMore.value = false
        window.closeFpiAppPop && window?.closeFpiAppPop()
    } else {
        currentMenuInfo.bottom = info.code
        isShowMore.value = false
        if (info.url) {
            router.push({
                path: info.url,
            })
        } else {
            if (info.subs && info.subs[0]) {
                onClickTopMenu(info.subs[0])
            }
        }
    }
}

// 点击顶部菜单
const onClickTopMenu = (info: any) => {
    if (info.isOutlink) {
        const path = info.url.includes('http')
            ? info.url
            : `${config.outLinkDefaultRootPath}${info.url}`
        window.open(path)
    } else {
        currentMenuInfo.bottom = info.parentCode
        currentMenuInfo.top = info.code
        router.push({
            path: info.url,
        })
    }
}
</script>

<style lang="scss" scoped>
.top-menus {
    position: absolute;
    z-index: 3;
    height: 36px;
    left: 50%;
    transform: translateX(-50%);
    top: 121px;
    display: flex;
    align-items: center;
    justify-content: center;

    .item {
        height: 100%;
        min-width: 116px;
        background-repeat: no-repeat;
        background-size: 100% 100%;
        display: flex;
        justify-content: center;
        align-items: flex-start;
        background-position: 0 8px;
        cursor: pointer;

        &.active {
            .text {
                color: #fff;
                background: unset;
                background-clip: unset;
                -webkit-text-fill-color: unset;
            }
        }

        .text {
            padding-top: 2px;
            font-size: 24px;
            line-height: 24px;
            height: 24px;
            font-family: PangMenZhengDao;
            background: linear-gradient(
                180deg,
                rgba(255, 255, 255, 1) 0%,
                rgba(16, 208, 160, 1) 100%
            );
            color: rgba(255, 255, 255, 1);
            background-clip: text;
            -webkit-text-fill-color: transparent;

            &:hover {
                background: linear-gradient(
                    180deg,
                    rgba(226, 226, 226, 1) 0%,
                    rgba(3, 109, 82, 1) 100%
                );
                background-clip: text;
            }
        }
    }
}

.bottom-menus-more-pop {
    width: 1580px;
    // height: 373px;
    // max-height: 400px; /* 设置一个足够大的最大高度 */
    position: absolute;
    z-index: 6;
    left: 50%;
    bottom: 0px;
    transform: translateX(-50%);
    background-repeat: no-repeat;
    background-size: 100% 100%;
    padding: 24px 220px 60px;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: flex-start;
    align-content: flex-start;
    gap: 24px;

    .item {
        width: 168px;
        height: 64px;
        background-repeat: no-repeat;
        background-size: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 28px;
        font-family: PangMenZhengDao;
        line-height: 28px;
        letter-spacing: 2px;
        cursor: pointer;
        user-select: none;

        &.active {
            .text {
                color: #fff;
            }
        }

        .text {
            // background: linear-gradient(
            //     180deg,
            //     rgba(255, 255, 255, 1) 0%,
            //     rgba(179, 255, 252, 1) 100%
            // );
            // color: rgba(255, 255, 255, 1);
            // background-clip: text;
            // -webkit-text-fill-color: transparent;
            color: rgba(16, 208, 160, 1);

            &:hover {
                // background: unset;
                // color: rgba(255, 255, 255, 1);
                // background-clip: unset;
                // -webkit-text-fill-color: rgba(255, 255, 255, 1);
                color: rgba(6, 194, 147, 0.8);
            }
        }
    }
}

.bottom-menus {
    position: absolute;
    width: 1200px;
    height: 44px;
    z-index: 7;
    left: 50%;
    transform: translateX(-50%);
    bottom: 0;
    display: flex;
    // justify-content: space-between;
    justify-content: center;
    align-items: center;

    .item {
        font-size: 28px;
        font-family: PangMenZhengDao;
        line-height: 28px;
        height: 28px;
        cursor: pointer;
        color: rgba(16, 208, 160, 1);
        letter-spacing: 2px;
        user-select: none;
        margin-left: 20px;
        white-space: nowrap;

        &.active {
            color: rgba(255, 255, 255, 1);
        }

        &:hover {
            color: rgba(6, 194, 147, 0.8);
        }
    }
}
</style>
